package me.yricky.mayu.ui.file_list

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.material.Icon
import androidx.compose.material.OutlinedTextField
import androidx.compose.material.Text
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.rounded.Close
import androidx.compose.material.icons.rounded.Folder
import androidx.compose.material.icons.rounded.InsertDriveFile
import androidx.compose.material.icons.rounded.Search
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.unit.dp
import me.yricky.mayu.ui.LazyColumnWithScrollBar
import java.io.File

/**
 * @author Yricky
 * @date 2022/4/14
 */
@Composable
fun FileBrowseModel.Page(){
    val filter by viewState.filter.collectAsState()
    val files by viewState.files.collectAsState()
    var dir by remember { mutableStateOf(viewState.currDir.value) }
    Column(
        Modifier
            .fillMaxSize()
    ) {
        OutlinedTextField(
            filter,
            { setFilter( it.trim()) },
            label = { Text("filter") },
            modifier = Modifier.padding(8.dp,0.dp).fillMaxWidth(),
            trailingIcon = { if(filter!=""){
                Icon(Icons.Rounded.Close,"",Modifier.clickable { setFilter("") })
            } },
            leadingIcon = { Icon(Icons.Rounded.Search,"") },
        )
        FileList(
            Modifier
            .weight(1f)
            .fillMaxWidth()
            .padding(8.dp,4.dp),
            files,
            icons
        ){ f->
            if(f.isDirectory){
                dir = f
                setDir(f)
            }else{
                openMethod?.invoke(f)
            }
        }
        BasicTextField("${dir.canonicalPath}${File.separator.takeIf { !dir.canonicalPath.endsWith(it) } ?: ""}",{
            dir = File(it)
            if(dir.isDirectory){
                setDir(dir)
            }
        }, modifier = Modifier.fillMaxWidth().padding(8.dp,4.dp), singleLine = true)
    }
}

@Composable
fun FileList(
    modifier: Modifier = Modifier,
    files:List<File> = emptyList(),
    icons:((File)->ImageVector?)? = null,
    onClick:(File)->Unit = {}
){
    LazyColumnWithScrollBar(modifier) {
        items(files){
            val f = it
            Row(
                Modifier
                .fillMaxWidth()
                .clickable {
                    onClick(f)
                }
                .padding(0.dp,4.dp)
            ) {
                Icon(
                    if(f.isDirectory){ Icons.Rounded.Folder }
                    else{ icons?.invoke(f) ?: Icons.Rounded.InsertDriveFile },
                    "icon",
                    modifier = Modifier.size(24.dp))
                Text(f.name)
            }
        }
    }
}